import json
import random

from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt

from web.forms.account import UserInfoModelForm, SendSmsForm, LoginSmsForm
from web.models import UserInfo

# Create your views here.
"""
用户账户相关功能：注册、登录、注销、短信
"""


def register(request):
    """ 注册 """
    form = UserInfoModelForm()
    return render(request, 'web/register.html', {'form': form})


@csrf_exempt
def send_sms(request):
    """ 发送短信 """
    form = SendSmsForm(request=request, data=request.POST)
    # 短信发送与写入redis，实现于forms的勾子方法里，主要就是为了验证错误时对应该于相应的字段位置
    if form.is_valid():
        return JsonResponse({"status": True, "count_down_seconds": settings.COUNT_DOWN_SECONDS})
    return JsonResponse({"status": False, "errors": form.errors})


def register_submit(request):
    """ 注册提交 """
    form = UserInfoModelForm(data=request.POST)
    try:
        max_obj = UserInfo.objects.latest('id')
        form.instance.user_code = '8' + "%05d" % (max_obj.id + 1)
    except UserInfo.DoesNotExist:
        form.instance.user_code = '800001'
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'errors': form.errors, 'msg': '提交返回失败!'},
                        json_dumps_params={'ensure_ascii': False})


def login_sms(request):
    """ 手机短信登录 """
    form = LoginSmsForm()
    return render(request, 'web/login_sms.html', {'form': form})
